<template>
  <div class="voice-tts-page">
    <!-- 上半部分：操作框 -->
    <div class="panel">
      <div class="panel-header">
        <div class="panel-tabs">
          <el-button class="tab-btn" size="large" @click="goToVoiceClone">
            声音克隆
          </el-button>
          <el-button class="tab-btn tab-btn--active" size="large">
            文字转语音
          </el-button>
        </div>
      </div>
      <el-form label-width="120px" class="form">
        <el-form-item label="选择音色">
          <el-select 
            v-model="selectedVoiceId" 
            placeholder="请选择音色" 
            filterable 
            class="voice-select"
            popper-class="voice-select-dropdown"
            clearable
            @change="handleVoiceChange"
          >
            <el-option 
              v-for="v in voiceOptions" 
              :key="`${v.id}`" 
              :label="v.name" 
              :value="`${v.id}`" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="输入文本">
          <el-input
            v-model="text"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="请输入要合成的文本"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="synthLoading" @click="handleSynthesize" class="synth-btn">
            开始合成
            <span class="points-text">0.5积分</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 下半部分：列表/历史 -->
    <div class="panel">
      <div class="panel-header" style="display: flex; justify-content: space-between; align-items: center;">
        <h3>合成历史</h3>
        <el-button 
          type="primary" 
          size="small" 
          @click="fetchList"
          :loading="listLoading"
          style="margin-left: auto;"
        >
          刷新列表
        </el-button>
      </div>
      <el-table :data="records" v-loading="listLoading">
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column prop="voice_name" label="音色名称" />
        <el-table-column prop="text" label="文本（前40字）">
          <template #default="{ row }">
            {{ row.text?.slice(0, 40) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag type="info">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <div v-if="row.audio_url" style="display: flex; flex-direction: column; gap: 8px;">
              <audio :src="row.audio_url" controls style="width: 180px; height: 32px;"></audio>
              <el-button 
                size="small" 
                type="primary" 
                @click="downloadAudio(row.audio_url, row.id)"
                style="font-size: 12px;"
              >
                下载音频
              </el-button>
            </div>
            <span v-else style="color: #999;">暂无音频</span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" />
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="page"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { apiRequest, API_CONFIG } from '@/config/api'

const router = useRouter()

const selectedVoiceId = ref('')
const voiceOptions = ref([])
const text = ref('')
const synthLoading = ref(false)

// 监听选择变化
watch(selectedVoiceId, (newVal) => {
  console.log('选择的音色ID:', newVal)
})

// 监听文本变化
watch(text, (newVal) => {
  console.log('文本内容变化:', newVal)
})


const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const records = ref([])
const listLoading = ref(false)

function goToVoiceClone() {
  router.push('/voice/clone')
}

async function fetchVoiceOptions() {
  // 直接复用 voiceClone/list 作为下拉选
  try {
    const resp = await apiRequest(API_CONFIG.ENDPOINTS.VOICE_CLONE_LIST, {
      method: 'GET',
      params: { page: 1, pageSize: 100 }
    })
    if (resp.code === 200) {
      const list = resp.data?.list || []
      console.log('Voice options data:', list) // 调试用
      voiceOptions.value = list.map(it => ({ 
        id: String(it.voice_id ?? it.id ?? ''),
        name: it.name || it.voice_name || `音色-${it.voice_id || it.id}`
        
      }))
      console.log('Processed voice options:', voiceOptions.value) // 调试用
    }
  } catch (error) {
    console.error('获取音色列表失败:', error)
  }
}

async function handleSynthesize() {
  console.log('提交时的数据检查:')
  console.log('selectedVoiceId:', selectedVoiceId.value)
  console.log('text原始值:', text.value)
  console.log('text长度:', text.value ? text.value.length : 0)
  console.log('text去空格后:', text.value ? text.value.trim() : '')
  console.log('text去空格后长度:', text.value ? text.value.trim().length : 0)
  
  if (!selectedVoiceId.value) {
    ElMessage.error('请先选择音色')
    return
  }
  if (!text.value || !text.value.trim()) {
    ElMessage.error('请输入要合成的文本')
    return
  }
  synthLoading.value = true
  try {
    const submitData = { voiceId: selectedVoiceId.value, voiceText: text.value.trim() }
    console.log('提交的数据:', submitData)
    
    const resp = await apiRequest('/text2voice/submit', {
      method: 'POST',
      body: JSON.stringify(submitData)
    })
    if (resp.code === 200) {
      ElMessage.success('已提交合成任务')
      // 清空表单
      selectedVoiceId.value = ''
      text.value = ''
      fetchList()
    } else {
      ElMessage.error(resp.msg || '合成失败')
    }
  } finally {
    synthLoading.value = false
  }
}

function handleVoiceChange(val) {
  // 规范化为字符串，确保 v-model 同步
  if (val != null) selectedVoiceId.value = String(val)
}

async function fetchList() {
  listLoading.value = true
  try {
    const resp = await apiRequest('/text2voice/list', {
      method: 'GET',
      params: { page: page.value, pageSize: pageSize.value }
    })
    if (resp.code === 200) {
      records.value = Array.isArray(resp.data?.list) ? resp.data.list : []
      // 同步使用后端返回的分页信息
      total.value = Number(resp.data?.pagination?.total || 0)
      page.value = Number(resp.data?.pagination?.page || page.value)
      pageSize.value = Number(resp.data?.pagination?.pageSize || pageSize.value)
      // 调试：打印状态值
      console.log('列表数据:', records.value)
      records.value.forEach((item, index) => {
        console.log(`第${index + 1}条记录状态:`, item.status, typeof item.status)
      })
    }
  } finally {
    listLoading.value = false
  }
}

function handlePageChange(p) {
  page.value = p
  fetchList()
}

// 下载音频文件
function downloadAudio(audioUrl, audioId) {
  if (!audioUrl) {
    ElMessage.warning('音频文件不存在')
    return
  }
  
  try {
    // 创建一个临时的 a 标签来触发下载
    const link = document.createElement('a')
    link.href = audioUrl
    link.download = `tts_audio_${audioId}.mp3` // 设置下载文件名
    link.target = '_blank'
    
    // 添加到页面并触发点击
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    
    ElMessage.success('开始下载音频文件')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}



onMounted(() => {
  fetchVoiceOptions()
  fetchList()
})
</script>

<style scoped>
.voice-tts-page {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 20px;
}

.panel {
  background: linear-gradient(145deg, #1e1e24, #23232a);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 16px;
  padding: 24px;
  color: #fff;
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.05);
}

.panel h2, .panel h3 {
  margin: 0 0 20px 0;
  color: #fff;
  font-weight: 600;
  font-size: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-tabs {
  display: flex;
  gap: 12px;
}

/* 顶部“声音克隆 / 文字转语音”Tab 样式，避免两个按钮都看起来像激活态 */
.panel-tabs :deep(.tab-btn) {
  background: transparent !important;
  border: 1px solid #409eff !important;
  color: #409eff !important;
  font-weight: 500;
}

.panel-tabs :deep(.tab-btn--active) {
  background: #409eff !important;
  color: #fff !important;
}

.form { 
  max-width: 720px; 
}

.pagination { 
  margin-top: 20px; 
  text-align: right; 
}

/* 优化音色选择框样式 */
:deep(.voice-select) {
  width: 100%;
  max-width: 400px;
}

:deep(.voice-select .el-input__wrapper) {
  background: #2a2a30;
  border: 1px solid #404040;
  border-radius: 4px;
  box-shadow: none;
  transition: border-color 0.2s ease;
  padding: 0 12px;
  height: 38px;
}

:deep(.voice-select .el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.voice-select .el-input.is-focus .el-input__wrapper) {
  border-color: #409eff;
}

:deep(.voice-select .el-input__inner) {
  background: transparent;
  color: #fff;
  font-size: 14px;
  font-weight: 400;
  border: none;
  height: 36px;
  line-height: 36px;
}

:deep(.voice-select .el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5);
  font-weight: 400;
}

:deep(.voice-select .el-select__caret) {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  transition: all 0.3s ease;
}

:deep(.voice-select .el-select__caret.is-reverse) {
  transform: rotate(180deg);
}

/* 文本输入框优化 */
:deep(.el-textarea .el-textarea__inner) {
  background: linear-gradient(145deg, #16161a, #1a1a20);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  color: #fff;
  font-size: 14px;
  line-height: 1.6;
  padding: 16px;
  transition: all 0.3s ease;
  resize: vertical;
  min-height: 120px;
}

:deep(.el-textarea .el-textarea__inner:hover) {
  border-color: rgba(64, 158, 255, 0.5);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

:deep(.el-textarea .el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 
    0 6px 16px rgba(0, 0, 0, 0.3),
    0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-textarea .el-textarea__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}



/* 表格无边框与分隔线 */
:deep(.el-table),
:deep(.el-table th),
:deep(.el-table td) {
  background: #23232a !important;
  color: #fff !important;
  border: none !important;
}
:deep(.el-table__inner-wrapper::before),
:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--group::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before) {
  background-color: transparent !important;
}
:deep(.el-table td),
:deep(.el-table th.is-leaf) { border-bottom: none !important; }
:deep(.el-table--border .el-table__cell) { border-right: none !important; }

/* 分页去白边：按钮、页码、跳转输入 */
:deep(.el-pagination) {
  background: #23232a !important;
  padding: 8px 12px;
  border-radius: 8px;
  border: none !important;
}
:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next),
:deep(.el-pagination button) {
  background: #1b1b1f !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}
:deep(.el-pagination .el-pager li) {
  background: #1b1b1f !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}
:deep(.el-pagination .el-pager li.is-active) {
  background: #409eff !important;
  color: #fff !important;
}
:deep(.el-pagination .el-pagination__jump .el-input__wrapper) {
  background: #0f0f12 !important; /* 跳转输入黑色 */
  border: none !important;
  box-shadow: none !important;
}
:deep(.el-pagination .el-input__wrapper.is-focus) { box-shadow: none !important; }
:deep(.el-pagination .el-input__inner) { color: #fff !important; }

/* 按钮蓝色 */
:deep(.el-button),
:deep(.el-button--primary) {
  background: #409eff !important;
  border: none !important;
  color: #fff !important;
}

/* 合成按钮积分样式 */
.synth-btn {
  position: relative;
  padding-right: 80px !important;

  .points-text {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 12px;
    opacity: 1;
    padding-left: 12px;
    border-left: 1px solid rgba(255, 255, 255, 0.5);
  }
}
:deep(.el-button:hover),
:deep(.el-button--primary:hover) {
  background: #337ecc !important;
  color: #fff !important;
}
:deep(.el-button.is-disabled),
:deep(.el-button.is-disabled:hover) {
  background: #3a3a40 !important;
  color: #9aa0a6 !important;
  border: none !important;
}
</style>

<style>
/* 下拉框全局样式 - 不使用 scoped 确保覆盖 Element Plus */
.voice-select-dropdown {
  background: #2a2a30 !important;
  border: 1px solid #404040 !important;
  border-radius: 4px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
  padding: 2px !important;
  margin-top: 2px !important;
  /* 按内容自适应高度，如内容过多由内部滚动条控制 */
  overflow: visible !important;
  z-index: 9999 !important;
  pointer-events: auto !important;
}

.voice-select-dropdown .el-select-dropdown__item {
  background: transparent !important;
  color: #fff !important;
  height: 32px !important;
  line-height: 32px !important;
  padding: 0 12px !important;
  margin: 1px 2px !important;
  border-radius: 3px !important;
  font-size: 13px !important;
  font-weight: 400 !important;
  transition: background-color 0.2s ease !important;
  border: none !important;
  cursor: pointer !important;
  pointer-events: auto !important;
  user-select: none !important;
}

.voice-select-dropdown .el-select-dropdown__item:hover {
  background: #404040 !important;
}

.voice-select-dropdown .el-select-dropdown__item.selected {
  background: #409eff !important;
  color: #fff !important;
}

.voice-select-dropdown .el-select-dropdown__item.is-disabled {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.3) !important;
  cursor: not-allowed !important;
}

.voice-select-dropdown .el-select-dropdown__empty {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.5) !important;
  padding: 16px !important;
  text-align: center !important;
  font-size: 13px !important;
  font-style: italic !important;
}

/* 下拉框滚动条扁平化 */
.voice-select-dropdown .el-scrollbar__bar.is-vertical {
  width: 2px !important;
  right: 0px !important;
}

.voice-select-dropdown .el-scrollbar__bar.is-vertical .el-scrollbar__thumb {
  background: #666 !important;
  border-radius: 0 !important;
}

/* 移除 Popper 箭头 */
.voice-select-dropdown.el-popper[data-popper-placement] .el-popper__arrow {
  display: none !important;
}

/* 确保下拉框无边框 */
.voice-select-dropdown,
.voice-select-dropdown * {
  outline: none !important;
}
</style>
